const app = getApp()
import api from '../../utils/api'
const DEFAULT_PAGE1 = 0;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //等待框
    waitHidden: true,
    navBarHeight: app.globalData.navBarHeight, //导航栏高度
    menuBotton: app.globalData.menuBotton, //导航栏距离顶部距离
    menuHeight: app.globalData.menuHeight, //导航栏高度
    //页面尺寸数据
    windowHeight: 0,
    screenHeight: 0,
    currentData: 0, //当前页面：0为在售，1为求购
    // list
    currentTab: 0, //预设当前项的值
    scrollLeft: 0, //tab标题的滚动条位置
    select: [{
        id: 0,
        name: "热门",
        iconNotSelect: '../../images/icon_hot_black.png',
        iconSelect: '../../images/icon_hot_white.png',
        sellShow: true, // 在售页面显示
        buyShow: false // 求购页面不显示
      },
      {
        id: 1,
        name: "手机数码",
        iconNotSelect: '../../images/icon_digital_black.png',
        iconSelect: '../../images/icon_digital_white.png',
        sellShow: true,
        buyShow: true
      }, {
        id: 2,
        name: "厨房厨具",
        iconNotSelect: '../../images/icon_cooker_black.png',
        iconSelect: '../../images/icon_cooker_white.png',
        sellShow: true,
        buyShow: true
      }, {
        id: 3,
        name: "家用电器",
        iconNotSelect: '../../images/icon_appliance_black.png',
        iconSelect: '../../images/icon_appliance_white.png',
        sellShow: true,
        buyShow: true
      }, {
        id: 4,
        name: "母婴",
        iconNotSelect: '../../images/icon_baby_black.png',
        iconSelect: '../../images/icon_baby_white.png',
        sellShow: true,
        buyShow: true
      },
      {
        id: 5,
        name: "图书",
        iconNotSelect: '../../images/icon_book_black.png',
        iconSelect: '../../images/icon_book_white.png',
        sellShow: true,
        buyShow: true
      }, {
        id: 6,
        name: "工会",
        iconNotSelect: '../../images/icon_gift_black.png',
        iconSelect: '../../images/icon_gift_white.png',
        sellShow: true,
        buyShow: false
      }, {
        id: 7,
        name: "其他",
        iconNotSelect: '../../images/icon_other_black.png',
        iconSelect: '../../images/icon_other_white.png',
        sellShow: true,
        buyShow: true
      }
    ], //下方选择项栏目

    goods: [], //物品列表
    pageNo: 1,
    isLastPage: false,
    noticeList: [],
    noticeListTotal: 0,
    newGoodsList: [],
    requestParameters: "", //存放请求参数
    mainScrollViewHeight: 1624, // mainScrollView的高度，用于下滑
    singleGoodItemHeight: 420, // 单个商品列表高度

    bookedStartpageX: 0,
    bookedCurrentView: DEFAULT_PAGE1,
    toView1: `new_${DEFAULT_PAGE1}`,
    showDialog: false,
    height: 1624,
    userId: '',
    dotShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    //设置屏幕尺寸数据
    this.setData({
      windowHeight: app.globalData.windowHeight,
      screenHeight: app.globalData.screenHeight,
      height: app.globalData.screenHeight,
      userId: wx.getStorageSync('logindata').data.id
    })

    if (this.data.requestParameters == "") {
      this.setData({
        requestParameters: options
      })
    }
    wx.setStorageSync('goods', [])
    wx.setStorageSync('newGoods', [])
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      pageNo: 1,
      goods: [],
      height: this.data.currentData=="0"?this.data.screenHeight+300:this.data.screenHeight
    })
    //初次加载
    this.requestGoodsList()
    if(this.data.currentData == 0) {
      this.getLatestDeal() // 大家都在买
      // 好物上新
      this.getLatestPost()
    } else if(this.data.currentData == 1) {
      this.getLatestPurchasePost()
    }
    // 个人中心提醒
    this.checkDealsDone()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  requestGoodsList: function (e) {
    var that = this
    // 显示等待框
    this.setData({
      waitHidden: false
    })
    //请求物品列表
    var category = that.data.currentTab
    var isIdle = that.data.currentData
    var httpApi = ""
    if (category == "0") {
      // 热门商品查询
      that.hotSelect()
    } else { // 商品列表查询
      if (isIdle == "0") { // 在售
        httpApi = api.getGoodsList
      } else if (isIdle == "1") { // 求购
        httpApi = api.getPurchaseGoodsList
      }

      wx.request({
        url: httpApi,
        method: "POST",
        data: {
          status: 1, // 待售中
          category: category,
          pageIndex: that.data.pageNo,
          pageSize: 20
        },
        header: {
          'content-type': 'application/json;charset=UTF-8',
          'token': wx.getStorageSync('token')
        },
        success(res) {
          that.setData({
            goods: [],
            height: that.data.height
          })
          if (res.data.data.records.length!=0) {
            for (var i = 0; i < res.data.data.records.length; i++) {
              var imgUrl = res.data.data.records[i].imgUrl
              var shot = res.data.data.records[i].title
              // var description = res.data.data.records[i].description
              var price = that.data.currentData == 0 ? res.data.data.records[i].price : res.data.data.records[i].bottomPrice
              var peakPrice = that.data.currentData == 0 ? "": res.data.data.records[i].peakPrice
              var userName = res.data.data.records[i].name + res.data.data.records[i].workno
              var goodsId = res.data.data.records[i].id
              // var goodsTime = res.data.data.records[i].releaseTime
              var thumbnailUrl = res.data.data.records[i].thumbnailUrl ? res.data.data.records[i].thumbnailUrl : imgUrl? imgUrl:"../../images/此处应有图.jpeg"
              var userId = that.data.currentData == 0 ? res.data.data.records[i].sellerId : res.data.data.records[i].buyerId
              var tmp = {
                imgUrl,
                shot,
                // description,
                price,
                peakPrice,
                userName,
                goodsId,
                // goodsTime,
                thumbnailUrl,
                userId
              }


              that.data.goods.push(tmp)
            }


            that.setData({
              goods: that.data.goods,
              isLastPage: res.data.data.pageIndex == res.data.data.totalPages,
              waitHidden: true,
            })
            //用于页面下滑高度调整
            var length = that.data.currentData == 0 ? Math.ceil(res.data.data.records.length / 2) - 1 : Math.ceil(res.data.data.records.length / 2) - 2
            var heightAdd = ""
            if (that.data.currentData == 0) { // 在售页面
              if (res.data.data.records.length == 0) {
                heightAdd = that.data.singleGoodItemHeight * 1
              } else {
                heightAdd = that.data.singleGoodItemHeight * (length <= 0 ? 0 : length)
              }
              wx.createSelectorQuery().select('#item0 .swiper-item').boundingClientRect((rect) => {
                that.setData({
                  height: that.data.height + heightAdd
                })
              }).exec()
            } else if (that.data.currentData == 1) { // 求购页面
              if (res.data.data.records.length == 0) {
                heightAdd = 0
              } else {
                heightAdd = that.data.singleGoodItemHeight * (length <= 0 ? 0 : length)
              }
              
            wx.createSelectorQuery().select('#item1 .swiper-item').boundingClientRect((rect) => {
              that.setData({
                height: that.data.height + heightAdd
              })
            }).exec()
            }

            wx.setStorage({
              data: that.data.goods,
              key: 'goods',
            })
          } else {
            that.setData({
              goods: [],
              isLastPage: true,
              waitHidden: true
            })
            wx.setStorage({
              data: [],
              key: 'goods',
            })
          }
        }
      })

    }

  },
  // 点击标题切换当前页时改变样式 // 切换“热门”、“手机数码”。。。
  swichNav: function (e) {
    var cur = e.currentTarget.dataset.current; //查询标题序号
    this.checkCor(e);
    if (this.data.currentTab == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur,
        goods: new Array,
        //清除pageNo
        pageNo: 1,
        isLastPage: false,
        height: this.data.currentData=="0"?this.data.screenHeight+300:this.data.screenHeight // 初始化
      })
      if (cur == 0) {
        // 热门商品查询
        this.hotSelect()
      } else {
        this.requestGoodsList()
      }
    }
  },
  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function (e) {
    this.setData({
      scrollLeft: this.data.scrollLeft + 70 * (e.currentTarget.dataset.current - this.data.currentTab)
    })
  },
  goToAdd: function (e) {
    this.setData({
      showDialog: false
    })
    wx.navigateTo({
      url: '/pages/goodsAdd/goodsAdd?isIdle=true',
    })
  },
  goToAddPurchaseInfo: function (e) {
    this.setData({
      showDialog: false
    })
    wx.navigateTo({
      url: '/pages/goodsAdd/goodsAdd?isIdle=false',
    })
  },
  goToCenter: function (e) {
    wx.navigateTo({
      // url: '/pages/marketCenter/marketCenter',
      url: "/pages/marketCenter2/markerCenter2"
    })
  },
  goToDetail: function (e) {
    var index = e.currentTarget.dataset.index
    var goods = wx.getStorageSync('goods')
    this.addHit(goods[index].goodsId)
    wx.navigateTo({
      url: "/pages/goodsDetail/goodsDetail?index=" + index + '&isIdle=' + this.data.currentData,
    })
  },
  goToDetail2: function (e) {
    var index = e.currentTarget.dataset.index
    var goods = wx.getStorageSync('newGoods')
    this.addHit(goods[index].goodsId)
    wx.navigateTo({
      url: "/pages/goodsDetail/goodsDetail?latestPostIndex=" + index + '&isIdle=' + this.data.currentData,
    })
  },
  goBack: function (e) {
    wx.navigateBack({
      delta: 1,
    })
  },
  changePageTab: function (e) {
    var that = this
    if (that.data.currentData == 0 && e.detail.source == "touch") {
      that.setData({
        currentData: 1,
        currentTab:1,
        goods: new Array,
        //清除pageNo
        pageNo: 1,
        isLastPage: false,
        newGoodsList: [],
        noticeList:[],
        height: that.data.screenHeight, // 初始化
        scrollLeft: 0,
        waitHidden: false
      })
    } else if (that.data.currentData == 1 && e.detail.source == "touch") {
      that.setData({
        currentData: 0,
        currentTab:0,
        goods: new Array,
        newGoodsList: [],
        noticeList:[],
        //清除pageNo
        pageNo: 1,
        isLastPage: false,
        height: that.data.screenHeight + 300, // 初始化
        scrollLeft: 0,
        waitHidden: false
      })
    }
    if (that.data.currentData == "0") { // 在售页面
      that.getLatestDeal() // 大家都在买 
      that.getLatestPost() // 好物上新
    } else if (that.data.currentData == "1") { // 求购页面
      that.getLatestPurchasePost() // 最新发布 
    }
    that.requestGoodsList()

    setTimeout(function() {
      that.setData({
        waitHidden: true
      },500)
    })
  },
  /**
   * 点击切换，滑块index赋值，切换“在售”与“求购”
   */
  swichNav1: function (e) {
    const that = this;
    if (that.data.currentData == e.currentTarget.dataset.current) {
      return false;
    } else {
      that.setData({
        currentData: e.currentTarget.dataset.current,
        currentTab: e.currentTarget.dataset.current == 0 ? 0 : 1,
        goods: new Array,
        //清除pageNo
        pageNo: 1,
        isLastPage: false,
        height: e.currentTarget.dataset.current == 0?that.data.screenHeight+300:that.data.screenHeight, // 初始化
        scrollLeft: 0
      })
    }
    // if (e.currentTarget.dataset.current == "0") { // 在售页面
    //   that.getLatestDeal() // 大家都在买 
    //   this.getLatestPost() // 好物上新
    // } else if (e.currentTarget.dataset.current == "1") { // 求购页面
    //   that.getLatestPurchasePost() // 最新发布 
    // }
    // that.requestGoodsList()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function (e) {
    var that = this
    if (!that.data.isLastPage) {
      this.setData({
        pageNo: this.data.pageNo + 1,
        waitHidden: false
      })
      //商品列表查询
      this.requestGoodsList()
    }
    this.setData({
      waitHidden: true
    })

  },
  // onPullDownRefresh: function (e) {
  //   this.setData({
  //     pageNo: 1,
  //     goods: new Array
  //   })
  //   this.requestGoodsList()
  // },

  touchBookedStart(e) {
    this.bookedStartpageX = e.changedTouches[0].pageX;
  },

  touchBookedEnd(e) {
    const moveX = e.changedTouches[0].pageX - this.bookedStartpageX;
    const maxPage = this.data.newGoodsList.length - 1;
    if (Math.abs(moveX) >= 10) {
      if (moveX > 0) {
        this.bookedCurrentView = this.bookedCurrentView !== 0 ? this.bookedCurrentView - 1 : 0;
      } else {
        this.bookedCurrentView = this.bookedCurrentView !== maxPage ? this.bookedCurrentView + 1 : maxPage;
      }
    }
    this.setData({
      toView1: `new_${this.bookedCurrentView}`
    });
  },

  /**
   * 控制 pop 的打开关闭
   * 该方法作用有2:
   * 1：点击弹窗以外的位置可消失弹窗
   * 2：用到弹出或者关闭弹窗的业务逻辑时都可调用
   */
  toggleDialog() {
    this.setData({
      showDialog: !this.data.showDialog
    });
  },
  toShowDialog() {
    this.setData({
      showDialog: true
    });
  },
  // 大家都在买
  getLatestDeal() {
    var that = this
    that.setData({
      noticeList: [],
      noticeListTotal: 0
    })
    wx.request({
      url: api.getLatestDeal + "?is_demand=" + that.data.currentData,
      method: "GET",
      success(res) {
        if (res.data.data.length !== 0) {
          for (var i = 0; i < res.data.data.length; i++) {
            var index = i
            var buyer = res.data.data[i].fname ? res.data.data[i].fname : "某人"
            var price = res.data.data[i].price
            var goodsName = res.data.data[i].title
            var time = res.data.data[i].orderTime
            var passTime = that.humandate(that.getUnixTime(time))
            var noticeList = {
              buyer,
              price,
              goodsName,
              passTime,
              index
            }
            that.data.noticeList.push(noticeList)
          }
          that.setData({
            noticeList: that.data.noticeList,
            noticeListTotal: res.data.data.length
          })
        } else {
          // console.log("no data")
        }
      }
    })
  },
  // 日期转时间戳
  getUnixTime: function (dateStr) {
    let newstr = dateStr.replace(/-/g, '/')
    let date = new Date(newstr)
    let time_str = date.getTime().toString()
    return time_str.substr(0, 10)
  },
  // 时间戳之间 相减  当前时间的时间戳 - 结束时间的时间戳
  humandate: function (time) {
    var nowTimestamp = Date.parse(new Date())
    var timeNow = Math.round(nowTimestamp / 1000)
    //var time1 = Date.parse(new Date()) / 1000;
    var s = timeNow - time;
    if (s < 0) {
      s = Math.abs(s);
    }
    if (s > 31536000) {
      return parseInt(s / 31536000) + '年';
    } else if (s > 2592000) {
      return parseInt(s / 2592000) + '月';
    } else if (s > 86400) {
      return parseInt(s / 86400) + '天';
    } else if (s > 3600) {
      return parseInt(s / 3600) + '小时';
    } else if (s > 60) {
      return parseInt(s / 60) + '分钟';
    } else {
      // return parseInt(s) + '秒';
      return '刚刚';
    }
  },
  // 热门商品查询
  hotSelect: function () {
    var that = this
    wx.request({
      url: api.hotSelect + "?is_demand=" + that.data.currentData + "&pageSize=20" + "&currentPage=" + this.data.pageNo,
      method: "GET",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'token': wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.data.records.length!=0) {
          for (var i = 0; i < res.data.data.records.length; i++) {
            var imgUrl = res.data.data.records[i].imgUrl
            var shot = res.data.data.records[i].title
            var description = res.data.data.records[i].description
            var price = res.data.data.records[i].price
            var userName = res.data.data.records[i].name + res.data.data.records[i].workno
            var goodsId = res.data.data.records[i].id
            var goodsTime = res.data.data.records[i].releaseTime
            var thumbnailUrl = res.data.data.records[i].thumbnailUrl
            var tmp = {
              imgUrl,
              shot,
              description,
              price,
              userName,
              goodsId,
              goodsTime,
              thumbnailUrl
            }


            that.data.goods.push(tmp)
          }
          var heightAdd = that.data.singleGoodItemHeight * Math.ceil(res.data.data.records.length / 2 - 1)
          that.setData({
            goods: that.data.goods,
            isLastPage: !res.data.data.totalPages || res.data.data.currentPage == res.data.data.totalPages,
            waitHidden: true,
          })

          wx.createSelectorQuery().select('#item0 .swiper-item').boundingClientRect((rect) => {
            that.setData({
              height: that.data.height + heightAdd
            })
          }).exec()
          wx.setStorage({
            data: that.data.goods,
            key: 'goods',
          })
        } else {
          that.setData({
            isLastPage: true,
            waitHidden: true
          })
          wx.setStorage({
            data: [],
            key: 'goods',
          })
        }
      }
    })
  },
  // 在售页面-好物上新
  getLatestPost: function () {
    var that = this
    wx.request({
      url: api.getLatestPost + "?is_demand=" + that.data.currentData,
      method: "GET",
      success(res) {
        that.setData({
          newGoodsList: []
        })
        //限制展示5个
        var total = 0
        if (res.data.data.length > 5) {
          total = 5
        } else {
          total = res.data.data.length
        }
        for (var i = 0; i < total; i++) {
          var imgUrl = res.data.data[i].imgUrl
          var price = res.data.data[i].price
          var goodsId = res.data.data[i].id
          var goodsTime = res.data.data[i].releaseTime
          var shot = res.data.data[i].title
          var description = res.data.data[i].description
          var userName = res.data.data[i].sellerId
          var workno = res.data.data[i].workno
          var thumbnailUrl = res.data.data[i].thumbnailUrl
          var tmp = {
            imgUrl,
            price,
            goodsId,
            goodsTime,
            shot,
            description,
            userName,
            thumbnailUrl,workno
          }
          that.data.newGoodsList.push(tmp)
        }

        that.setData({
          newGoodsList: that.data.newGoodsList
        })
        wx.setStorage({
          data: that.data.newGoodsList,
          key: 'newGoods',
        })
      }
    })
  },
  // 求购页面-最新发布
  getLatestPurchasePost: function () {
    var that = this
    wx.request({
      url: api.getLatestPost + "?is_demand=" + that.data.currentData,
      method: "GET",
      success(res) {
        that.setData({
          noticeList: new Array,
          noticeListTotal: 0
        })
        if (res.data.data) {
          for (var i = 0; i < res.data.data.length; i++) {
            var index = i
            var buyer = res.data.data[i].fname ? res.data.data[i].fname : "某人"
            var price = res.data.data[i].peakPrice
            var goodsName = res.data.data[i].title
            var time = res.data.data[i].releaseTime
            var passTime = that.humandate(that.getUnixTime(time))
            var noticeList = {
              index,
              buyer,
              price,
              goodsName,
              passTime
            }
            that.data.noticeList.push(noticeList)
          }
          that.setData({
            noticeList: that.data.noticeList,
            noticeListTotal: res.data.data.length
          })
        } else {
          // console.log("no data")
        }
      }
    })
  },
  // 浏览量计数
  addHit: function (id) {
    wx.request({
      url: api.countHits,
      method: "POST",
      data: {
        id: id,
        is_demand: this.data.currentData
      },
      header: {
        'content-type': 'application/json;charset=UTF-8',
        'token': wx.getStorageSync('token')
      },
      success(res) {
        // console.log("addHit")
      }
    })
  },

  
    // 个人中心提醒
    checkDealsDone: function() {
      var that = this
      wx.request({
        url: api.getDealing + '?user_id=' + that.data.userId,
        method: "GET",
        success(res) {
          if (res.data.data[0]) {
            var status = res.data.data[0].dealing
            if (status == 1) {// 有未完成交易
              that.setData({
                dotShow: true
              })
            } else {// 无
              that.setData({
                dotShow: false
              })
            }
          } else{
            that.setData({
              dotShow: false
            })
          }
        }
      })
    }

})